<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>智慧教室 - By:杨春</title>
    <script src="https://unpkg.com/mqtt/dist/mqtt.min.js"></script>
    <script src="https://cdn.tailwindcss.com"></script>
    <link href="https://cdn.jsdelivr.net/npm/font-awesome@4.7.0/css/font-awesome.min.css" rel="stylesheet">
    
    <!-- 配置Tailwind自定义颜色 -->
    <script>
        tailwind.config = {
            theme: {
                extend: {
                    colors: {
                        primary: '#06b6d4',
                        secondary: '#22d3ee',
                        accent: '#0ea5e9',
                        dark: '#0f172a',
                        'glass': 'rgba(15, 23, 42, 0.7)',
                        'light-sensor': '#fde047' // 新增光照传感器主题色（黄色系）
                    },
                    fontFamily: {
                        sans: ['Inter', 'system-ui', 'sans-serif'],
                    },
                }
            }
        }
    </script>
    
    <style type="text/tailwindcss">
        @layer utilities {
            .content-auto {
                content-visibility: auto;
            }
            .text-shadow {
                text-shadow: 0 0 8px rgba(6, 182, 212, 0.8);
            }
            .glow {
                box-shadow: 0 0 15px rgba(6, 182, 212, 0.5);
            }
            .glass-effect {
                backdrop-filter: blur(10px);
                background-color: rgba(15, 23, 42, 0.6);
            }
            .control-btn {
                transition: all 0.3s ease;
                position: relative;
                overflow: hidden;
            }
            .control-btn::after {
                content: '';
                position: absolute;
                top: 50%;
                left: 50%;
                width: 0;
                height: 0;
                background: rgba(255, 255, 255, 0.1);
                border-radius: 50%;
                transform: translate(-50%, -50%);
                transition: width 0.6s ease, height 0.6s ease;
            }
            .control-btn:active::after {
                width: 300px;
                height: 300px;
                opacity: 0;
            }
            .status-indicator {
                width: 12px;
                height: 12px;
                border-radius: 50%;
                display: inline-block;
            }
            .pulse {
                animation: pulse 2s infinite;
            }
            @keyframes pulse {
                0% {
                    transform: scale(0.95);
                    box-shadow: 0 0 0 0 rgba(6, 182, 212, 0.7);
                }
                70% {
                    transform: scale(1);
                    box-shadow: 0 0 0 10px rgba(6, 182, 212, 0);
                }
                100% {
                    transform: scale(0.95);
                    box-shadow: 0 0 0 0 rgba(6, 182, 212, 0);
                }
            }
            .float {
                animation: float 6s ease-in-out infinite;
            }
            @keyframes float {
                0% { transform: translateY(0px); }
                50% { transform: translateY(-15px); }
                100% { transform: translateY(0px); }
            }
        }
    </style>
</head>

<body class="min-h-screen bg-dark text-gray-100 overflow-x-hidden font-sans">
    <!-- 粒子背景容器 -->
    <div id="particles" class="fixed inset-0 z-0 opacity-40"></div>
    
    <!-- 渐变覆盖层 -->
    <div class="fixed inset-0 z-10 bg-gradient-to-b from-dark/80 via-dark/60 to-dark/90 pointer-events-none"></div>
    
    <!-- 主容器 -->
    <div class="relative z-20 container mx-auto px-4 py-8 max-w-6xl">
        <!-- 头部 -->
        <header class="text-center mb-12 mt-6">
            <div class="inline-block relative mb-4">
                <i class="fa fa-graduation-cap text-primary text-5xl float"></i>
                <div class="absolute -inset-1 bg-gradient-to-r from-primary to-accent rounded-full blur opacity-30"></div>
            </div>
            <h1 class="text-[clamp(2rem,5vw,3rem)] font-bold text-primary text-shadow mb-2">智慧教室控制系统</h1>
            <p class="text-secondary/80 text-lg">实时监控与智能控制中心</p>
            
            <!-- 连接状态 -->
            <div class="mt-6 inline-flex items-center gap-2 px-4 py-2 rounded-full glass-effect border border-primary/30">
                <span id="connection-status" class="status-indicator bg-yellow-500 pulse"></span>
                <span id="connection-text">连接中...</span>
                <span class="text-xs text-gray-400 ml-2">MQTT 客户端</span>
            </div>
        </header>
        
        <!-- 环境监测卡片（新增光照卡片，改为3列布局） -->
        <section class="grid grid-cols-1 md:grid-cols-3 gap-6 mb-8">
            <!-- 温度卡片 -->
            <div class="glass-effect rounded-2xl p-6 glow border border-primary/30 transform transition-all duration-300 hover:-translate-y-1 hover:shadow-lg">
                <div class="flex justify-between items-start">
                    <div>
                        <h2 class="text-xl font-semibold flex items-center">
                            <i class="fa fa-thermometer-half text-orange-400 mr-2"></i>温度监测
                        </h2>
                        <p class="text-gray-400 text-sm mt-1">实时环境温度</p>
                    </div>
                    <div class="w-10 h-10 rounded-full bg-orange-400/20 flex items-center justify-center">
                        <i class="fa fa-fire text-orange-400"></i>
                    </div>
                </div>
                
                <div class="mt-6 flex items-end">
                    <span id="temperature" class="text-5xl font-bold text-orange-400">Loading...</span>
                    <span class="text-xl mb-1 ml-2 text-orange-400/80">°C</span>
                </div>
                
                <div class="mt-4 h-2 w-full bg-gray-700/50 rounded-full overflow-hidden">
                    <div id="temp-progress" class="h-full bg-gradient-to-r from-yellow-400 to-orange-500 rounded-full" style="width: 0%"></div>
                </div>
                
                <div class="flex justify-between mt-2 text-xs text-gray-400">
                    <span>16°C</span>
                    <span>舒适区间</span>
                    <span>32°C</span>
                </div>
            </div>
            
            <!-- 湿度卡片 -->
            <div class="glass-effect rounded-2xl p-6 glow border border-primary/30 transform transition-all duration-300 hover:-translate-y-1 hover:shadow-lg">
                <div class="flex justify-between items-start">
                    <div>
                        <h2 class="text-xl font-semibold flex items-center">
                            <i class="fa fa-tint text-blue-400 mr-2"></i>湿度监测
                        </h2>
                        <p class="text-gray-400 text-sm mt-1">实时环境湿度</p>
                    </div>
                    <div class="w-10 h-10 rounded-full bg-blue-400/20 flex items-center justify-center">
                        <i class="fa fa-tint text-blue-400"></i>
                    </div>
                </div>
                
                <div class="mt-6 flex items-end">
                    <span id="humidity" class="text-5xl font-bold text-blue-400">Loading...</span>
                    <span class="text-xl mb-1 ml-2 text-blue-400/80">%RH</span>
                </div>
                
                <div class="mt-4 h-2 w-full bg-gray-700/50 rounded-full overflow-hidden">
                    <div id="humidity-progress" class="h-full bg-gradient-to-r from-blue-400 to-cyan-500 rounded-full" style="width: 0%"></div>
                </div>
                
                <div class="flex justify-between mt-2 text-xs text-gray-400">
                    <span>30%</span>
                    <span>舒适区间</span>
                    <span>70%</span>
                </div>
            </div>

            <!-- 新增：光照监测卡片 -->
            <div class="glass-effect rounded-2xl p-6 glow border border-primary/30 transform transition-all duration-300 hover:-translate-y-1 hover:shadow-lg">
                <div class="flex justify-between items-start">
                    <div>
                        <h2 class="text-xl font-semibold flex items-center">
                            <i class="fa fa-sun-o text-light-sensor mr-2"></i>光照监测
                        </h2>
                        <p class="text-gray-400 text-sm mt-1">实时环境光照</p>
                    </div>
                    <div class="w-10 h-10 rounded-full bg-light-sensor/20 flex items-center justify-center">
                        <i class="fa fa-sun-o text-light-sensor"></i>
                    </div>
                </div>
                
                <div class="mt-6 flex items-end">
                    <span id="light" class="text-5xl font-bold text-light-sensor">Loading...</span>
                    <span class="text-xl mb-1 ml-2 text-light-sensor/80">lux</span> <!-- lux：光照强度单位 -->
                </div>
                
                <div class="mt-4 h-2 w-full bg-gray-700/50 rounded-full overflow-hidden">
                    <div id="light-progress" class="h-full bg-gradient-to-r from-light-sensor to-yellow-500 rounded-full" style="width: 0%"></div>
                </div>
                
                <div class="flex justify-between mt-2 text-xs text-gray-400">
                    <span>0 lux</span>
                    <span>适宜区间</span>
                    <span>5000 lux</span>
                </div>
            </div>
        </section>
        
        <!-- 控制区域 -->
        <section class="grid grid-cols-1 md:grid-cols-2 gap-6 mb-10">
            <!-- 灯光控制 -->
            <div class="glass-effect rounded-2xl p-6 glow border border-primary/30 transform transition-all duration-300 hover:-translate-y-1 hover:shadow-lg">
                <div class="flex justify-between items-start mb-6">
                    <div>
                        <h2 class="text-xl font-semibold flex items-center">
                            <i class="fa fa-lightbulb-o text-yellow-400 mr-2"></i>灯光控制
                        </h2>
                        <p class="text-gray-400 text-sm mt-1">教室照明系统</p>
                    </div>
                    <div id="light-status" class="px-3 py-1 rounded-full text-xs font-medium bg-gray-700/50">
                        未初始化
                    </div>
                </div>
                
                <div class="flex justify-center">
                    <!-- 灯光按钮：添加data-state="off" -->
                    <button id="LightOn" class="control-btn ..." data-state="off">
                        <i class="fa fa-power-off mr-2"></i>开 灯
                    </button>
                </div>
                
                <div class="mt-6 grid grid-cols-3 gap-3">
                    <button class="py-2 rounded-lg bg-gray-800/50 hover:bg-primary/20 transition-colors text-sm">
                        <i class="fa fa-sun-o mr-1"></i>明亮
                    </button>
                    <button class="py-2 rounded-lg bg-gray-800/50 hover:bg-primary/20 transition-colors text-sm">
                        <i class="fa fa-moon-o mr-1"></i>柔和
                    </button>
                    <button class="py-2 rounded-lg bg-gray-800/50 hover:bg-primary/20 transition-colors text-sm">
                        <i class="fa fa-magic mr-1"></i>自动
                    </button>
                </div>
            </div>
            
            <!-- 报警控制 -->
            <div class="glass-effect rounded-2xl p-6 glow border border-primary/30 transform transition-all duration-300 hover:-translate-y-1 hover:shadow-lg">
                <div class="flex justify-between items-start mb-6">
                    <div>
                        <h2 class="text-xl font-semibold flex items-center">
                            <i class="fa fa-bell text-red-400 mr-2"></i>报警控制
                        </h2>
                        <p class="text-gray-400 text-sm mt-1">安全警报系统</p>
                    </div>
                    <div id="beep-status" class="px-3 py-1 rounded-full text-xs font-medium bg-gray-700/50">
                        未初始化
                    </div>
                </div>
                
                <div class="flex justify-center">
                    <!-- 报警按钮：添加data-state="off" -->
                    <button id="BeepOn" class="control-btn ..." data-state="off">
                        <i class="fa fa-exclamation-triangle mr-2"></i>报 警
                    </button>
                </div>
                
                <div class="mt-6 grid grid-cols-2 gap-3">
                    <button class="py-2 rounded-lg bg-gray-800/50 hover:bg-red-500/20 transition-colors text-sm">
                        <i class="fa fa-shield mr-1"></i>测试系统
                    </button>
                    <button class="py-2 rounded-lg bg-gray-800/50 hover:bg-primary/20 transition-colors text-sm">
                        <i class="fa fa-history mr-1"></i>警报记录
                    </button>
                </div>
            </div>
        </section>
        
        <!-- 系统信息 -->
        <footer class="glass-effect rounded-xl p-4 text-center text-gray-400 text-sm border border-primary/20">
            <p>智慧教室控制系统 | By:杨春</p>
            <p class="mt-1">MQTT 客户端 ID: <span id="client-id-display">连接中...</span></p>
        </footer>
    </div>

    <!-- 通知提示框 -->
    <div id="notification" class="fixed bottom-6 right-6 z-50 px-6 py-3 rounded-lg glass-effect border border-primary/50 transform translate-y-20 opacity-0 transition-all duration-500 flex items-center gap-3 max-w-xs">
        <i id="notification-icon" class="fa fa-info-circle text-primary text-xl"></i>
        <div>
            <h3 id="notification-title" class="font-medium text-white">通知标题</h3>
            <p id="notification-message" class="text-sm text-gray-300">通知内容</p>
        </div>
    </div>

    <script>
        // 创建粒子背景
        function createParticles() {
            const particlesContainer = document.getElementById('particles');
            const particleCount = 80;
            
            for (let i = 0; i < particleCount; i++) {
                const particle = document.createElement('div');
                
                // 随机属性
                const size = Math.random() * 3 + 1;
                const posX = Math.random() * 100;
                const posY = Math.random() * 100;
                const duration = Math.random() * 40 + 30;
                const delay = Math.random() * 10;
                const opacity = Math.random() * 0.6 + 0.2;
                
                particle.style.cssText = `
                    position: absolute;
                    width: ${size}px;
                    height: ${size}px;
                    background-color: rgba(6, 182, 212, ${opacity});
                    border-radius: 50%;
                    top: ${posY}%;
                    left: ${posX}%;
                    box-shadow: 0 0 ${size * 5}px rgba(6, 182, 212, 0.5);
                    animation: float ${duration}s ease-in-out ${delay}s infinite;
                `;
                
                particlesContainer.appendChild(particle);
            }
        }
        
        // 显示通知
        function showNotification(title, message, type = 'info') {
            const notification = document.getElementById('notification');
            const titleEl = document.getElementById('notification-title');
            const messageEl = document.getElementById('notification-message');
            const iconEl = document.getElementById('notification-icon');
            
            // 设置内容
            titleEl.textContent = title;
            messageEl.textContent = message;
            
            // 设置图标和颜色
            notification.classList.remove('border-primary/50', 'border-green-500/50', 'border-red-500/50', 'border-yellow-500/50');
            iconEl.classList.remove('text-primary', 'text-green-500', 'text-red-500', 'text-yellow-500');
            iconEl.classList.remove('fa-info-circle', 'fa-check-circle', 'fa-exclamation-circle', 'fa-exclamation-triangle');
            
            switch(type) {
                case 'success':
                    notification.classList.add('border-green-500/50');
                    iconEl.classList.add('text-green-500', 'fa-check-circle');
                    break;
                case 'error':
                    notification.classList.add('border-red-500/50');
                    iconEl.classList.add('text-red-500', 'fa-exclamation-circle');
                    break;
                case 'warning':
                    notification.classList.add('border-yellow-500/50');
                    iconEl.classList.add('text-yellow-500', 'fa-exclamation-triangle');
                    break;
                default:
                    notification.classList.add('border-primary/50');
                    iconEl.classList.add('text-primary', 'fa-info-circle');
            }
            
            // 显示通知
            notification.classList.remove('translate-y-20', 'opacity-0');
            notification.classList.add('translate-y-0', 'opacity-100');
            
            // 3秒后隐藏
            setTimeout(() => {
                notification.classList.remove('translate-y-0', 'opacity-100');
                notification.classList.add('translate-y-20', 'opacity-0');
            }, 3000);
        }
        
        // 更新进度条（新增光照进度条逻辑）
        function updateProgressBars(temp, humidity, light) {
            // 1. 温度进度条 (16-32°C 映射到 0-100%)
            const tempPercent = Math.min(100, Math.max(0, ((parseFloat(temp) - 16) / 16) * 100));
            document.getElementById('temp-progress').style.width = `${tempPercent}%`;
            
            // 2. 湿度进度条 (30-70% 映射到 0-100%)
            const humidityPercent = Math.min(100, Math.max(0, ((parseFloat(humidity) - 30) / 40) * 100));
            document.getElementById('humidity-progress').style.width = `${humidityPercent}%`;
            
            // 3. 新增：光照进度条 (0-5000 lux 映射到 0-100%)
            const lightPercent = Math.min(100, Math.max(0, (parseFloat(light) / 5000) * 100));
            document.getElementById('light-progress').style.width = `${lightPercent}%`;

            // 光照异常提醒（过强/过弱）
            if (parseFloat(light) > 4000) {
                showNotification('光照警告', `当前光照过强: ${light} lux`, 'warning');
            } else if (parseFloat(light) < 500) {
                showNotification('光照提醒', `当前光照过弱: ${light} lux`, 'info');
            }
        }

		function getQueryParam(param) {
            const url = window.location.href;
            const regex = new RegExp('[?&]' + param + '=([^&#]*)');
            const results = regex.exec(url);
            if (results === null) {
                return null;
            } else {
                return decodeURIComponent(results[1]) || '';
            }
        }

        // MQTT 相关配置和逻辑
        const deviceId = getQueryParam('did') || 'springu'; // 默认设备ID
        const clientId = 'mqttjs_' + Math.random().toString(16).substr(2, 8);
        const host = 'ws://39.103.98.89:8083/mqtt';
        
        // 显示客户端ID
        document.getElementById('client-id-display').textContent = clientId;
        
        const options = {
            keepalive: 60,
            clientId: clientId,
            protocolId: 'MQTT',
            protocolVersion: 4,
            clean: true,
            reconnectPeriod: 1000,
            connectTimeout: 30 * 1000,
            will: {
                topic: 'WillMsg',
                payload: 'Connection Closed abnormally..!',
                qos: 0,
                retain: false
            },
        };

        // 连接 MQTT 服务器
        const client = mqtt.connect(host, options);
        const connectionStatus = document.getElementById('connection-status');
        const connectionText = document.getElementById('connection-text');

        // 连接状态更新
        function updateConnectionStatus(status) {
            connectionStatus.className = 'status-indicator pulse';
            
            switch(status) {
                case 'connected':
                    connectionStatus.classList.add('bg-green-500');
                    connectionText.textContent = '已连接';
                    showNotification('连接成功', '已成功连接到MQTT服务器', 'success');
                    break;
                case 'connecting':
                    connectionStatus.classList.add('bg-yellow-500');
                    connectionText.textContent = '连接中...';
                    break;
                case 'error':
                    connectionStatus.classList.add('bg-red-500');
                    connectionText.textContent = '连接失败';
                    showNotification('连接失败', '无法连接到MQTT服务器', 'error');
                    break;
            }
        }

        // 连接成功
        client.on('connect', function() {
            updateConnectionStatus('connected');
            
            // 订阅传感器主题
            client.subscribe(deviceId + '/sensor/+', function(err) {
                if (!err) {
                    console.log('订阅传感器主题成功');
                    showNotification('订阅成功', '已成功订阅传感器数据', 'info');
                } else {
                    showNotification('订阅失败', '无法订阅传感器主题', 'error');
                }
            });

            // 订阅设备状态主题
            client.subscribe(deviceId + '/state/+', function(err) {
                if (!err) {
                    console.log('订阅状态主题成功');
                } else {
                    showNotification('订阅失败', '无法订阅设备状态主题', 'error');
                }
            });
        });

        // 连接错误
        client.on('error', function() {
            updateConnectionStatus('error');
        });

        // 重新连接
        client.on('reconnect', function() {
            updateConnectionStatus('connecting');
            showNotification('正在重连', '尝试重新连接到服务器', 'warning');
        });

        // 接收消息（新增光照数据处理逻辑）
        client.on('message', function(topic, message) {
            console.log('收到消息: ' + topic + ' : ' + message.toString());
            
            // 1. 温度湿度数据处理
            if (topic === deviceId + '/sensor/dht11') {
                const data = message.toString();
                const parts = data.split('_');
                
                if (parts.length === 2) {
                    const temp = parts[0];
                    const humidity = parts[1];
                    // 获取当前光照数据（避免进度条更新时缺少参数）
                    const currentLight = document.getElementById('light').textContent === 'Loading...' ? '0' : document.getElementById('light').textContent;
                    
                    document.getElementById('temperature').innerText = temp;
                    document.getElementById('humidity').innerText = humidity;
                    
                    // 同步更新所有进度条（含光照）
                    updateProgressBars(temp, humidity, currentLight);
                    
                    // 温度过高提醒
                    if (parseFloat(temp) > 30) {
                        showNotification('温度警告', `当前温度过高: ${temp}°C`, 'warning');
                    }
                }
            }
            // 2. 新增：光照数据处理
            else if (topic === deviceId + '/sensor/light') {
                const lightValue = message.toString();
                // 获取当前温度/湿度数据（避免进度条更新时缺少参数）
                const currentTemp = document.getElementById('temperature').textContent === 'Loading...' ? '20' : document.getElementById('temperature').textContent;
                const currentHumidity = document.getElementById('humidity').textContent === 'Loading...' ? '50' : document.getElementById('humidity').textContent;
                
                // 更新光照显示
                document.getElementById('light').innerText = lightValue;
                // 同步更新所有进度条
                updateProgressBars(currentTemp, currentHumidity, lightValue);
            }
            // 3. 灯光状态处理
            else if(topic === deviceId + '/state/led') {
                const state = message.toString();
                const lightBtn = document.getElementById('LightOn');
                const lightStatus = document.getElementById('light-status');
                
                if(state === '1') {
                    lightBtn.innerHTML = '<i class="fa fa-power-off mr-2"></i>关 灯';
                    lightBtn.classList.remove('border-primary/50');
                    lightBtn.classList.add('border-yellow-400');
                    lightBtn.classList.remove('text-primary');
                    lightBtn.classList.add('text-yellow-400');
                    
                    lightStatus.textContent = '已开启';
                    lightStatus.classList.remove('bg-gray-700/50', 'bg-red-500/30');
                    lightStatus.classList.add('bg-green-500/30', 'text-green-400');
                    
                    showNotification('灯光状态', '教室灯光已开启', 'info');
                } else {
                    lightBtn.innerHTML = '<i class="fa fa-power-off mr-2"></i>开 灯';
                    lightBtn.classList.remove('border-yellow-400');
                    lightBtn.classList.add('border-primary/50');
                    lightBtn.classList.remove('text-yellow-400');
                    lightBtn.classList.add('text-primary');
                    
                    lightStatus.textContent = '已关闭';
                    lightStatus.classList.remove('bg-green-500/30', 'text-green-400');
                    lightStatus.classList.add('bg-red-500/30', 'text-red-400');
                    
                    showNotification('灯光状态', '教室灯光已关闭', 'info');
                }
            }
            // 4. 报警状态处理
            else if(topic === deviceId + '/state/beep') {
                const state = message.toString();
                const beepBtn = document.getElementById('BeepOn');
                const beepStatus = document.getElementById('beep-status');
                
                if(state === '1') {
                    beepBtn.innerHTML = '<i class="fa fa-volume-off mr-2"></i>静 音';
                    beepBtn.classList.add('animate-pulse');
                    
                    beepStatus.textContent = '报警中';
                    beepStatus.classList.remove('bg-gray-700/50', 'bg-green-500/30', 'text-green-400');
                    beepStatus.classList.add('bg-red-500/30', 'text-red-400');
                    
                    showNotification('报警状态', '警报已触发', 'warning');
                } else {
                    beepBtn.innerHTML = '<i class="fa fa-exclamation-triangle mr-2"></i>报 警';
                    beepBtn.classList.remove('animate-pulse');
                    
                    beepStatus.textContent = '已静音';
                    beepStatus.classList.remove('bg-red-500/30', 'text-red-400');
                    beepStatus.classList.add('bg-green-500/30', 'text-green-400');
                    
                    showNotification('报警状态', '警报已静音', 'info');
                }
            }
        });
        /*
        // 灯光控制按钮
        document.getElementById('LightOn').addEventListener('click', function() {
            let message = 'b';  // 关灯命令
            
            if(this.innerHTML.includes('开 灯')) {
                message = 'a'; // 开灯命令
            }

            client.publish(deviceId + '/cmd', message);
        });

        // 报警控制按钮
        document.getElementById('BeepOn').addEventListener('click', function() {
            let message = 'd'; // 静音命令
            
            if(this.innerHTML.includes('报 警')) {
                message = 'c'; // 报警命令
            }

            client.publish(deviceId + '/cmd', message);
        });
        */

        // 灯光控制按钮（修复版）
        document.getElementById('LightOn').addEventListener('click', function() {
            // 1. 获取当前状态（off/on）
            const currentState = this.getAttribute('data-state');
            let command, newState, newText, newBorder, newColor;

            // 2. 根据当前状态决定命令和新状态
            if (currentState === 'off') {
                // 当前关闭 → 发送开灯命令（a）
                command = 'a';
                newState = 'on';
                newText = '<i class="fa fa-power-off mr-2"></i>关 灯';
                newBorder = 'border-yellow-400'; // 开灯后边框变黄
                newColor = 'text-yellow-400';    // 开灯后文字变黄
            } else {
                // 当前开启 → 发送关灯命令（b）
                command = 'b';
                newState = 'off';
                newText = '<i class="fa fa-power-off mr-2"></i>开 灯';
                newBorder = 'border-primary/50'; // 关灯后边框恢复默认
                newColor = 'text-primary';       // 关灯后文字恢复默认
            }

            // 3. 手动更新按钮状态、文本和样式
            this.setAttribute('data-state', newState);
            this.innerHTML = newText;
            // 先移除旧样式，再添加新样式
            this.classList.remove('border-primary/50', 'border-yellow-400', 'text-primary', 'text-yellow-400');
            this.classList.add(newBorder, newColor);

            // 4. 发布命令并打印日志（验证是否发送正确）
            console.log('灯光命令：', command, '（当前状态：', newState, '）');
            client.publish(deviceId + '/cmd', command, function(err) {
                if (err) console.error('灯光命令发送失败：', err);
            });
        });

        // 报警控制按钮（修复版）
        document.getElementById('BeepOn').addEventListener('click', function() {
            // 1. 获取当前状态（off/on）
            const currentState = this.getAttribute('data-state');
            let command, newState, newText, newAnim;

            // 2. 根据当前状态决定命令和新状态
            if (currentState === 'off') {
                // 当前静音 → 发送报警命令（c）
                command = 'c';
                newState = 'on';
                newText = '<i class="fa fa-volume-off mr-2"></i>静 音';
                newAnim = 'animate-pulse'; // 报警时添加闪烁动画
            } else {
                // 当前报警 → 发送静音命令（d）
                command = 'd';
                newState = 'off';
                newText = '<i class="fa fa-exclamation-triangle mr-2"></i>报 警';
                newAnim = ''; // 静音后移除闪烁动画
        }

        // 3. 手动更新按钮状态、文本和样式
        this.setAttribute('data-state', newState);
        this.innerHTML = newText;
        // 先移除旧动画，再添加新动画
        this.classList.remove('animate-pulse');
        if (newAnim) this.classList.add(newAnim);

        // 4. 发布命令并打印日志（验证是否发送正确）
        console.log('报警命令：', command, '（当前状态：', newState, '）');
        client.publish(deviceId + '/cmd', command, function(err) {
            if (err) console.error('报警命令发送失败：', err);
        });
    });

        // 初始化
        window.addEventListener('load', function() {
            createParticles();
            updateConnectionStatus('connecting');
        });
    </script>
</body>
</html>